<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 20px;
        }
        .upload-box {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .upload-box input {
            display: block;
            margin-bottom: 10px;
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .upload-box button {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .upload-box button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>

<div class="upload-box">
    <h2>文件上传</h2>
    <form id="uploadForm">
        <label for="fileInput">选择文件：</label>
        <input type="file" id="fileInput" name="file" required>
        <button type="button" onclick="uploadFile()">上传文件</button>
    </form>
    <div id="responseMessage" style="margin-top: 20px; color: green;"></div>
</div>

<script>
    function uploadFile() {
        const fileInput = document.getElementById("fileInput");
        const file = fileInput.files[0]; // 获取选中的文件

        if (!file) {
            alert("请选择一个文件！");
            return;
        }

        const formData = new FormData();
        formData.append("file", file); // 将文件添加到 FormData

        // 向后端发送 POST 请求
        fetch("/admin/lesson/upload", {
            method: "POST",
            body: formData
        })
            .then((response) => response.json())
            .then((data) => {
                const responseMessage = document.getElementById("responseMessage");
                if (data.code === 1) {
                    responseMessage.style.color = "green";
                    responseMessage.textContent = "文件上传成功！文件路径：" + data.data;
                } else {
                    responseMessage.style.color = "red";
                    responseMessage.textContent = "上传失败：" + data.msg;
                }
            })
            .catch((error) => {
                console.error("上传出错：", error);
                const responseMessage = document.getElementById("responseMessage");
                responseMessage.style.color = "red";
                responseMessage.textContent = "文件上传失败，请稍后重试！";
            });
    }
</script>

</body>
</html>